/**
 * 搜索服务
 * Search Service
 */

const Note = require('../database/models/Note');
const File = require('../database/models/File');
const { query } = require('../database/connection');
const logger = require('../utils/logger');

class SearchService {
  constructor() {
    this.searchHistory = new Map(); // 用户搜索历史
    this.popularSearches = new Map(); // 热门搜索
  }

  /**
   * 全局搜索（笔记和文件）
   */
  async globalSearch(userId, keyword, options = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        type = 'all', // all, notes, files
        sortBy = 'relevance' // relevance, date, title
      } = options;

      const results = {
        notes: [],
        files: [],
        total: 0,
        pagination: {
          page,
          pageSize,
          totalPages: 0
        }
      };

      // 记录搜索历史
      this.recordSearchHistory(userId, keyword);

      if (type === 'all' || type === 'notes') {
        // 搜索笔记
        const notesResult = await this.searchNotes(userId, keyword, {
          page: type === 'notes' ? page : 1,
          pageSize: type === 'notes' ? pageSize : Math.ceil(pageSize / 2)
        });
        results.notes = notesResult.data || [];
      }

      if (type === 'all' || type === 'files') {
        // 搜索文件
        const filesResult = await this.searchFiles(userId, keyword, {
          page: type === 'files' ? page : 1,
          pageSize: type === 'files' ? pageSize : Math.ceil(pageSize / 2)
        });
        results.files = filesResult.data || [];
      }

      // 计算总数和分页信息
      results.total = results.notes.length + results.files.length;
      results.pagination.totalPages = Math.ceil(results.total / pageSize);

      // 排序结果
      if (type === 'all') {
        results.combined = this.sortSearchResults([...results.notes, ...results.files], sortBy);
      }

      return results;
    } catch (error) {
      logger.error('全局搜索失败 / Global search failed', {
        userId,
        keyword,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 搜索笔记
   */
  async searchNotes(userId, keyword, options = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        tags = [],
        dateRange = null,
        contentType = null,
        onlyFavorites = false
      } = options;

      // 构建搜索条件
      let whereConditions = ['user_id = ?', 'is_deleted = 0'];
      let queryParams = [userId];

      // 全文搜索
      if (keyword) {
        whereConditions.push('MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE)');
        queryParams.push(keyword);
      }

      // 标签筛选
      if (tags.length > 0) {
        const tagConditions = tags.map(() => 'JSON_CONTAINS(tags, ?)').join(' AND ');
        whereConditions.push(`(${tagConditions})`);
        tags.forEach(tag => queryParams.push(JSON.stringify(tag)));
      }

      // 内容类型筛选
      if (contentType) {
        whereConditions.push('content_type = ?');
        queryParams.push(contentType);
      }

      // 收藏筛选
      if (onlyFavorites) {
        whereConditions.push('is_favorite = 1');
      }

      // 日期范围筛选
      if (dateRange) {
        if (dateRange.start) {
          whereConditions.push('created_at >= ?');
          queryParams.push(dateRange.start);
        }
        if (dateRange.end) {
          whereConditions.push('created_at <= ?');
          queryParams.push(dateRange.end);
        }
      }

      // 构建查询SQL
      const offset = (page - 1) * pageSize;
      const orderBy = keyword 
        ? 'MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE) DESC, updated_at DESC'
        : 'updated_at DESC';

      if (keyword) {
        queryParams.push(keyword);
      }

      const searchSql = `
        SELECT id, title, content_type, tags, is_favorite, view_count, word_count, 
               created_at, updated_at,
               ${keyword ? 'MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE) as relevance' : '1 as relevance'}
        FROM notes 
        WHERE ${whereConditions.join(' AND ')}
        ORDER BY ${orderBy}
        LIMIT ? OFFSET ?
      `;

      if (keyword) {
        queryParams.push(keyword);
      }
      queryParams.push(pageSize, offset);

      const { rows } = await query(searchSql, queryParams);

      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM notes 
        WHERE ${whereConditions.join(' AND ')}
      `;
      const countParams = queryParams.slice(0, -2); // 移除LIMIT和OFFSET参数
      const { rows: countRows } = await query(countSql, countParams);
      const total = countRows[0].total;

      // 处理标签
      const processedRows = rows.map(note => {
        if (note.tags) {
          try {
            note.tags = JSON.parse(note.tags);
          } catch (e) {
            note.tags = [];
          }
        } else {
          note.tags = [];
        }
        
        // 添加搜索结果类型
        note.resultType = 'note';
        
        return note;
      });

      return {
        data: processedRows,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      logger.error('搜索笔记失败 / Search notes failed', {
        userId,
        keyword,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 搜索文件
   */
  async searchFiles(userId, keyword, options = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        fileType = null,
        dateRange = null,
        sizeRange = null
      } = options;

      // 构建搜索条件
      let whereConditions = ['user_id = ?', 'is_deleted = 0'];
      let queryParams = [userId];

      // 文件名搜索
      if (keyword) {
        whereConditions.push('(filename LIKE ? OR original_name LIKE ?)');
        queryParams.push(`%${keyword}%`, `%${keyword}%`);
      }

      // 文件类型筛选
      if (fileType) {
        whereConditions.push('file_type = ?');
        queryParams.push(fileType);
      }

      // 日期范围筛选
      if (dateRange) {
        if (dateRange.start) {
          whereConditions.push('created_at >= ?');
          queryParams.push(dateRange.start);
        }
        if (dateRange.end) {
          whereConditions.push('created_at <= ?');
          queryParams.push(dateRange.end);
        }
      }

      // 文件大小范围筛选
      if (sizeRange) {
        if (sizeRange.min) {
          whereConditions.push('file_size >= ?');
          queryParams.push(sizeRange.min);
        }
        if (sizeRange.max) {
          whereConditions.push('file_size <= ?');
          queryParams.push(sizeRange.max);
        }
      }

      // 构建查询SQL
      const offset = (page - 1) * pageSize;
      const searchSql = `
        SELECT id, filename, original_name, file_size, mime_type, file_type, 
               folder_path, is_public, download_count, thumbnail_path, 
               created_at, updated_at
        FROM files 
        WHERE ${whereConditions.join(' AND ')}
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;

      queryParams.push(pageSize, offset);
      const { rows } = await query(searchSql, queryParams);

      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total 
        FROM files 
        WHERE ${whereConditions.join(' AND ')}
      `;
      const countParams = queryParams.slice(0, -2);
      const { rows: countRows } = await query(countSql, countParams);
      const total = countRows[0].total;

      // 添加搜索结果类型
      const processedRows = rows.map(file => ({
        ...file,
        resultType: 'file'
      }));

      return {
        data: processedRows,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      logger.error('搜索文件失败 / Search files failed', {
        userId,
        keyword,
        error: error.message
      });
      throw error;
    }
  }  /**

   * 高级搜索
   */
  async advancedSearch(userId, searchParams) {
    try {
      const {
        keyword = '',
        title = '',
        content = '',
        tags = [],
        contentType = null,
        dateRange = null,
        onlyFavorites = false,
        sortBy = 'relevance',
        page = 1,
        pageSize = 20
      } = searchParams;

      // 构建复杂搜索条件
      let whereConditions = ['user_id = ?', 'is_deleted = 0'];
      let queryParams = [userId];

      // 关键词搜索（标题和内容）
      if (keyword) {
        whereConditions.push('MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE)');
        queryParams.push(keyword);
      }

      // 标题搜索
      if (title) {
        whereConditions.push('title LIKE ?');
        queryParams.push(`%${title}%`);
      }

      // 内容搜索
      if (content) {
        whereConditions.push('content LIKE ?');
        queryParams.push(`%${content}%`);
      }

      // 标签搜索
      if (tags.length > 0) {
        const tagConditions = tags.map(() => 'JSON_CONTAINS(tags, ?)').join(' OR ');
        whereConditions.push(`(${tagConditions})`);
        tags.forEach(tag => queryParams.push(JSON.stringify(tag)));
      }

      // 其他条件...
      if (contentType) {
        whereConditions.push('content_type = ?');
        queryParams.push(contentType);
      }

      if (onlyFavorites) {
        whereConditions.push('is_favorite = 1');
      }

      if (dateRange) {
        if (dateRange.start) {
          whereConditions.push('created_at >= ?');
          queryParams.push(dateRange.start);
        }
        if (dateRange.end) {
          whereConditions.push('created_at <= ?');
          queryParams.push(dateRange.end);
        }
      }

      // 排序逻辑
      let orderBy = 'updated_at DESC';
      if (sortBy === 'relevance' && keyword) {
        orderBy = 'MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE) DESC, updated_at DESC';
        queryParams.push(keyword);
      } else if (sortBy === 'title') {
        orderBy = 'title ASC';
      } else if (sortBy === 'created_at') {
        orderBy = 'created_at DESC';
      }

      // 执行搜索
      const offset = (page - 1) * pageSize;
      const searchSql = `
        SELECT id, title, content_type, tags, is_favorite, view_count, word_count, 
               created_at, updated_at,
               ${keyword ? 'MATCH(title, content) AGAINST(? IN NATURAL LANGUAGE MODE) as relevance' : '1 as relevance'}
        FROM notes 
        WHERE ${whereConditions.join(' AND ')}
        ORDER BY ${orderBy}
        LIMIT ? OFFSET ?
      `;

      if (keyword && sortBy !== 'relevance') {
        queryParams.push(keyword);
      }
      queryParams.push(pageSize, offset);

      const { rows } = await query(searchSql, queryParams);

      // 获取总数
      const countSql = `SELECT COUNT(*) as total FROM notes WHERE ${whereConditions.join(' AND ')}`;
      const countParams = queryParams.slice(0, -2);
      const { rows: countRows } = await query(countSql, countParams);
      const total = countRows[0].total;

      // 处理结果
      const processedRows = rows.map(note => {
        if (note.tags) {
          try {
            note.tags = JSON.parse(note.tags);
          } catch (e) {
            note.tags = [];
          }
        } else {
          note.tags = [];
        }
        return note;
      });

      return {
        data: processedRows,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize)
        },
        searchParams
      };
    } catch (error) {
      logger.error('高级搜索失败 / Advanced search failed', {
        userId,
        searchParams,
        error: error.message
      });
      throw error;
    }
  }

  /**
   * 搜索建议
   */
  async getSearchSuggestions(userId, keyword, limit = 10) {
    try {
      const suggestions = [];

      // 从笔记标题中获取建议
      const titleSql = `
        SELECT DISTINCT title 
        FROM notes 
        WHERE user_id = ? AND is_deleted = 0 AND title LIKE ?
        ORDER BY updated_at DESC
        LIMIT ?
      `;
      const { rows: titleRows } = await query(titleSql, [userId, `%${keyword}%`, limit]);
      
      titleRows.forEach(row => {
        suggestions.push({
          type: 'title',
          text: row.title,
          source: 'note_title'
        });
      });

      // 从标签中获取建议
      const tagsSql = `
        SELECT DISTINCT tags 
        FROM notes 
        WHERE user_id = ? AND is_deleted = 0 AND tags IS NOT NULL
        LIMIT 100
      `;
      const { rows: tagsRows } = await query(tagsSql, [userId]);
      
      const matchingTags = new Set();
      tagsRows.forEach(row => {
        try {
          const tags = JSON.parse(row.tags);
          tags.forEach(tag => {
            if (tag.toLowerCase().includes(keyword.toLowerCase())) {
              matchingTags.add(tag);
            }
          });
        } catch (e) {
          // 忽略解析错误
        }
      });

      Array.from(matchingTags).slice(0, limit - suggestions.length).forEach(tag => {
        suggestions.push({
          type: 'tag',
          text: tag,
          source: 'note_tag'
        });
      });

      return suggestions.slice(0, limit);
    } catch (error) {
      logger.error('获取搜索建议失败 / Get search suggestions failed', {
        userId,
        keyword,
        error: error.message
      });
      return [];
    }
  }

  /**
   * 记录搜索历史
   */
  recordSearchHistory(userId, keyword) {
    try {
      if (!keyword || keyword.trim().length === 0) return;

      const userHistory = this.searchHistory.get(userId) || [];
      const trimmedKeyword = keyword.trim();

      // 移除重复项
      const filteredHistory = userHistory.filter(item => item.keyword !== trimmedKeyword);
      
      // 添加新搜索记录
      filteredHistory.unshift({
        keyword: trimmedKeyword,
        timestamp: new Date(),
        count: 1
      });

      // 保持历史记录数量限制
      const maxHistory = 50;
      if (filteredHistory.length > maxHistory) {
        filteredHistory.splice(maxHistory);
      }

      this.searchHistory.set(userId, filteredHistory);

      // 更新热门搜索
      this.updatePopularSearches(trimmedKeyword);
    } catch (error) {
      logger.error('记录搜索历史失败 / Record search history failed', {
        userId,
        keyword,
        error: error.message
      });
    }
  }

  /**
   * 获取搜索历史
   */
  getSearchHistory(userId, limit = 20) {
    const userHistory = this.searchHistory.get(userId) || [];
    return userHistory.slice(0, limit);
  }

  /**
   * 清除搜索历史
   */
  clearSearchHistory(userId) {
    this.searchHistory.delete(userId);
  }

  /**
   * 更新热门搜索
   */
  updatePopularSearches(keyword) {
    const current = this.popularSearches.get(keyword) || { count: 0, lastUsed: new Date() };
    current.count++;
    current.lastUsed = new Date();
    this.popularSearches.set(keyword, current);

    // 清理过期的热门搜索（30天前）
    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    for (const [key, value] of this.popularSearches.entries()) {
      if (value.lastUsed < thirtyDaysAgo) {
        this.popularSearches.delete(key);
      }
    }
  }

  /**
   * 获取热门搜索
   */
  getPopularSearches(limit = 10) {
    const searches = Array.from(this.popularSearches.entries())
      .map(([keyword, data]) => ({ keyword, ...data }))
      .sort((a, b) => b.count - a.count)
      .slice(0, limit);

    return searches;
  }

  /**
   * 排序搜索结果
   */
  sortSearchResults(results, sortBy) {
    switch (sortBy) {
      case 'relevance':
        return results.sort((a, b) => (b.relevance || 0) - (a.relevance || 0));
      case 'date':
        return results.sort((a, b) => new Date(b.updated_at || b.created_at) - new Date(a.updated_at || a.created_at));
      case 'title':
        return results.sort((a, b) => (a.title || a.original_name || '').localeCompare(b.title || b.original_name || ''));
      default:
        return results;
    }
  }

  /**
   * 搜索统计
   */
  getSearchStats(userId) {
    const userHistory = this.searchHistory.get(userId) || [];
    const totalSearches = userHistory.reduce((sum, item) => sum + item.count, 0);
    const uniqueKeywords = userHistory.length;
    const recentSearches = userHistory.slice(0, 5);

    return {
      totalSearches,
      uniqueKeywords,
      recentSearches,
      popularSearches: this.getPopularSearches(5)
    };
  }
}

// 创建全局搜索服务实例
const searchService = new SearchService();

module.exports = searchService;